package com.almond.mq.config;

import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component
public class RabbitConfirmHandler {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        // 消息发送成功确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            String id = correlationData.getId();
//            ReturnedMessage returned = correlationData.getReturned();
//            Message message = returned.getMessage();
            if (ack) {
                // 消息成功发送到交换器处理
                System.out.println("消息成功发送到交换器");
            } else {
                // 消息发送失败处理
                System.out.println("消息发送失败：" + cause);
            }
        });

        // 消息返回回调，如路由键无法匹配队列
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            // 消息发送失败处理
            MessageProperties messageProperties = message.getMessageProperties();
            String messageId = messageProperties.getMessageId();
            System.out.println("msgId"+messageId);
            System.out.println("消息发送失败，消息：" + new String(message.getBody()) +
                    "，回复码：" + replyCode +
                    "，回复文本：" + replyText +
                    "，交换器：" + exchange +
                    "，路由键：" + routingKey);
        });


    }
}
